package com.sctvcloud.qingchuan.ui.fragment;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.canyinghao.canrefresh.CanRefreshLayout;
import com.ruihang.generalibrary.utils.ListUtils;
import com.sctvcloud.qingchuan.R;
import com.sctvcloud.qingchuan.application.Cache;
import com.sctvcloud.qingchuan.application.Constances;
import com.sctvcloud.qingchuan.beans.PoliticsItem;
import com.sctvcloud.qingchuan.beans.PoliticsListVo;
import com.sctvcloud.qingchuan.beans.PoliticsScreenCondition;
import com.sctvcloud.qingchuan.http.AbsNetCallBack;
import com.sctvcloud.qingchuan.http.NetUtils;
import com.sctvcloud.qingchuan.ui.adapter.PoliticsListAdapter;
import com.sctvcloud.qingchuan.ui.utils.DataUtils;
import com.sctvcloud.qingchuan.utils.UserManager;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.RequestBody;

/**
 * 问政数据列表
 */
public class PoliticsListFragment extends ColumnBaseFragment implements CanRefreshLayout.OnRefreshListener, CanRefreshLayout.OnLoadMoreListener {

    @BindView(R.id.fm_refresh)
    protected CanRefreshLayout refreshLayout;
    @BindView(R.id.can_content_view)
    protected RecyclerView recyclerView;

    private PoliticsListAdapter adapter;
    public static final String POLITICS_TYPE = "politics_type";
    private int politicsType = 0;
    private List<PoliticsItem> dataList = new ArrayList<>();
    private int pageNo = 1;
    private int pageSize = 10;
    private boolean hasNextPage = false;
    private PoliticsScreenCondition lastCondition;

    public PoliticsListFragment() {
        // Required empty public constructor
    }

    /**
     * 设置 问政加载类型
     *
     * @param politicsType 0：最新发布  1：最热问政  2：我的问政
     */
    public void setPoliticsType(int politicsType) {
        this.politicsType = politicsType;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
//        View view = inflater.inflate(R.layout.fragment_politics_list, container, false);
        View view = LayoutInflater.from(getContext()).inflate(R.layout.fragment_politics_list, container, false);
        ButterKnife.bind(this, view);
        return view;
    }


    @Override
    protected void initViews(View v, @Nullable Bundle savedInstanceState) {
        refreshLayout.setOnLoadMoreListener(this);
        refreshLayout.setOnRefreshListener(this);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false));
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        adapter = new PoliticsListAdapter(this, getContext(), null);
        recyclerView.setAdapter(adapter);
        refreshLayout.autoRefresh();
    }


    @Override
    public void onPause() {
        super.onPause();

    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            PoliticsScreenCondition condition = Cache.getInstance().getPcCondition();
            if (!(null != lastCondition && null != condition && condition.getInputKey().equalsIgnoreCase(lastCondition.getInputKey())
                    && (null != condition.getStatus() && null != lastCondition.getStatus() && condition.getStatus().getStatus() == lastCondition.getStatus().getStatus())
                    && (null != condition.getPoliticsObject() && null != lastCondition.getPoliticsObject() && condition.getPoliticsObject().getAuthorId() == lastCondition.getPoliticsObject().getAuthorId()))) {
                lastCondition = new PoliticsScreenCondition();
                lastCondition.setInputKey(condition.getInputKey());
                lastCondition.setPoliticsObject(condition.getPoliticsObject());
                lastCondition.setStatus(condition.getStatus());

                refreshLayout.autoRefresh();
            }
        }
    }

    @Override
    public void onLoadMore() {
        pageNo++;
        getData();
    }

    @Override
    public void onRefresh() {
        dataList.clear();
        pageNo = 1;
        getData();
    }


    /**
     * 修改筛选条件之后刷新数据
     */
    public void refreshScreenData() {
        PoliticsScreenCondition condition = Cache.getInstance().getPcCondition();
        if (!(null != lastCondition && null != condition && condition.getInputKey().equalsIgnoreCase(lastCondition.getInputKey())
                && (null != condition.getStatus() && null != lastCondition.getStatus() && condition.getStatus().getStatus() == lastCondition.getStatus().getStatus())
                && (null != condition.getPoliticsObject() && null != lastCondition.getPoliticsObject() && condition.getPoliticsObject().getAuthorId() == lastCondition.getPoliticsObject().getAuthorId()))) {
            lastCondition = new PoliticsScreenCondition();
            lastCondition.setInputKey(condition.getInputKey());
            lastCondition.setPoliticsObject(condition.getPoliticsObject());
            lastCondition.setStatus(condition.getStatus());

            refreshLayout.autoRefresh();
        }
    }

    /**
     * 获取数据
     */
    private void getData() {
        Map<String, Object> formMaildata = new HashMap<>();

        if (null != lastCondition) {
//            if (null != lastCondition.getPoliticsObject() && lastCondition.getPoliticsObject().getAuthorId() > 0) {
//                List<Long> ids = new ArrayList<>();
//                ids.add(lastCondition.getPoliticsObject().getAuthorId());
//                formMaildata.put("ids", ids);
//                formMaildata.put("selectType", 2);
//            } else {
                formMaildata.put("selectType", 1);
//            }
            if (null != lastCondition.getStatus() && lastCondition.getStatus().getStatus() > 0) {
                formMaildata.put("operationStatus", lastCondition.getStatus().getStatus());
            }
            if (!TextUtils.isEmpty(lastCondition.getInputKey())) {
                formMaildata.put("title", lastCondition.getInputKey());
            }
        } else {
            formMaildata.put("selectType", 1);
        }
        if (politicsType == 0) {
            formMaildata.put("orderField", "");
        } else if (politicsType == 1) {
            formMaildata.put("orderField", "hitCount");
        } else if (politicsType == 2) {
            if (null != UserManager.getInstance().getUser()) {
                formMaildata.put("userId", UserManager.getInstance().getUser().getUserId());
            }
        }

        formMaildata.put("pageNumber", pageNo);
        formMaildata.put("pageSize", pageSize);
        formMaildata.put("status", "1");
        RequestBody body = DataUtils.toRequestBody(formMaildata);
        NetUtils.getNetAdapter().toGetPoliticsListString(getOwnerName(), Constances.TENANT_ID, body, new AbsNetCallBack<String>(String.class) {
            @Override
            public void onSucStr(String news) {
                if (!TextUtils.isEmpty(news)) {
                    try {
                        PoliticsListVo bean = gson.fromJson(news, PoliticsListVo.class);
                        if (bean != null) {
                            hasNextPage = bean.isHasNextPage();
                            dataList.addAll(bean.getPageRecords());
                            initData(bean.getPageRecords());
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    onError(null, "数据异常");
                }
            }

            @Override
            public void onError(Throwable ex, String errorMsg) {
                toast(errorMsg);
                if (pageNo > 1) {
                    pageNo--;
                }
            }


            @Override
            public void onEnd() {
                onNetFinish();
            }
        });


    }

    private void initData(List<PoliticsItem> list) {
        if (ListUtils.isListValued(list)) {
            if (pageNo == 1) {
                adapter.setData(list);
            } else {
                adapter.addDatas(list);
            }
        } else {
            adapter.setData(list);
        }
    }

    private void onNetFinish() {
        refreshLayout.refreshComplete();
        refreshLayout.loadMoreComplete();
        refreshLayout.setLoadMoreEnabled(hasNextPage);

    }

}
